package com.beemans.common.utils

import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.net.Uri
import com.beemans.common.app.CommonConfig
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.RomUtils
import com.blankj.utilcode.util.Utils

/**
 * @author tiamosu
 * @date 2021/3/13
 */
private const val TAG = "AppStoreUtils"
private const val GOOGLE_PLAY_APP_STORE_PACKAGE_NAME = "com.android.vending"

private const val MARKET_PKG_NAME_HW = "com.huawei.appmarket"                   //华为
private const val MARKET_PKG_NAME_VIVO = "com.bbk.appstore"                     //VIVO
private const val MARKET_PKG_NAME_OPPO = "com.oppo.market"                      //OPPO
private const val MARKET_PKG_NAME_MI = "com.xiaomi.market"                      //小米
private const val MARKET_PKG_NAME_YYB = "com.tencent.android.qqdownloader"      //应用宝
private const val MARKET_PKG_NAME_360 = "com.qihoo.appstore"                    //360
private const val MARKET_PKG_NAME_BD = "com.baidu.appsearch"                    //百度助手
private const val MARKET_PKG_NAME_ALI = "com.wandoujia.phoenix2"                //阿里（豌豆荚）

private val marketPkgNameMap by lazy {
    mapOf(
        "huawei" to MARKET_PKG_NAME_HW,
        "vivo" to MARKET_PKG_NAME_VIVO,
        "oppo" to MARKET_PKG_NAME_OPPO,
        "xiaomi" to MARKET_PKG_NAME_MI,
        "yingyongbao" to MARKET_PKG_NAME_YYB,
        "360zhushou" to MARKET_PKG_NAME_360,
        "baiduzhushou" to MARKET_PKG_NAME_BD,
        "ali" to MARKET_PKG_NAME_ALI
    )
}

/**
 * 优先跳转到手机自带的应用市场
 *
 * @param pkgName           应用包名
 * @param marketPkgName     应用商店包名
 * @param isIncludeGoogle   是否包括 Google Play 商店
 * @return 跳转到应用商店的 Intent
 */
fun getAppStoreIntent(
    pkgName: String = CommonConfig.packageName,
    marketPkgName: String = "",
    isIncludeGoogle: Boolean = false
): Intent? {
    if (RomUtils.isSamsung()) { // 三星单独处理跳转三星市场
        val samsungAppStoreIntent = getSamsungAppStoreIntent(pkgName)
        if (samsungAppStoreIntent != null) return samsungAppStoreIntent
    }
    if (RomUtils.isLeeco()) { // 乐视单独处理跳转乐视市场
        val leecoAppStoreIntent = getLeecoAppStoreIntent(pkgName)
        if (leecoAppStoreIntent != null) return leecoAppStoreIntent
    }

    val newPackageName = if (pkgName.isBlank()) CommonConfig.packageName else pkgName
    val uri = Uri.parse("market://details?id=$newPackageName")
    val intent = Intent(Intent.ACTION_VIEW, uri).apply {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }

    val resolveInfoList = Utils.getApp().packageManager
        .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
    if (resolveInfoList.size == 0) {
        LogUtils.eTag(TAG, "No app store!")
        return null
    }

    //手机应用商店包名集合
    val phoneMarketPkgNameList = mutableListOf<String>()
    //手机自带的应用商店包名
    var appSystemMarketPkgName: String? = null
    //手机自带的应用商店以根据渠道定义的市场为主
    var appSystemMarketPkgNameByChannel: String? = null

    resolveInfoList.forEach { resolveInfo ->
        val packageName = resolveInfo.activityInfo.packageName
        phoneMarketPkgNameList.add(packageName)

        if (packageName != GOOGLE_PLAY_APP_STORE_PACKAGE_NAME && isAppSystem(packageName)) {
            appSystemMarketPkgName = packageName
            if (marketPkgNameMap.containsValue(packageName)) {
                appSystemMarketPkgNameByChannel = packageName
            }
        }
    }
    if (appSystemMarketPkgNameByChannel != null) {
        appSystemMarketPkgName = appSystemMarketPkgNameByChannel
    }

    //优先级：1、所需的应用商店；2、手机自带的应用商店；3、是否包含谷歌应用商店；4、用户自行选择
    when {
        marketPkgName.isNotBlank() && phoneMarketPkgNameList.contains(marketPkgName) -> {
            intent.setPackage(marketPkgName)
        }
        appSystemMarketPkgName?.isNotBlank() == true -> {
            intent.setPackage(appSystemMarketPkgName)
        }
        isIncludeGoogle && phoneMarketPkgNameList.contains(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME) -> {
            intent.setPackage(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME)
        }
    }
    return intent
}

/**
 * 跳转应用商店
 */
fun jumpToAppStore(
    pkgName: String = "",
    marketPkgName: String = "",
    isIncludeGoogle: Boolean = false,
    onFailed: () -> Boolean = { true }
) {
    val intent = getAppStoreIntent(pkgName, marketPkgName, isIncludeGoogle)
    if (intent == null || !ActivityUtils.startActivity(intent)) {
        if (onFailed.invoke()) {
            ToastUtils.showShort("无法打开应用市场")
        }
    }
}

/**
 * 跳转华为应用商店
 */
fun jumpToHwAppStore(
    pkgName: String = "",
    isIncludeGoogle: Boolean = false,
    onFailed: () -> Boolean = { true }
) {
    jumpToAppStore(pkgName, getMarketPkgNameByChannel("huawei"), isIncludeGoogle, onFailed)
}

/**
 * 判断手机是否存在华为应用商店
 */
fun isExistHwMarket(pkgName: String = CommonConfig.packageName): Boolean {
    return isExistMarketByChannel("huawei", pkgName)
}

/**
 * 手机中是否存在本机渠道相同的应用商店
 */
fun isExistMarketByChannel(
    channel: String,
    pkgName: String = CommonConfig.packageName
): Boolean {
    val uri = Uri.parse("market://details?id=$pkgName")
    val intent = Intent(Intent.ACTION_VIEW, uri).apply {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    val resolveInfoList = Utils.getApp().packageManager
        .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
    if (resolveInfoList.size == 0) {
        return false
    }
    if (channel.isBlank()) {
        return true
    }

    resolveInfoList.forEach { resolveInfo ->
        val packageName = resolveInfo.activityInfo.packageName
        if (packageName == getMarketPkgNameByChannel(channel)) {
            return true
        }
    }
    return false
}

fun getMarketPkgNameByChannel(channel: String): String {
    return marketPkgNameMap[channel] ?: ""
}

fun getAvailableIntentSize(intent: Intent): Int {
    return Utils.getApp().packageManager
        .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
        .size
}

fun isAppSystem(marketPkgName: String): Boolean {
    return if (marketPkgName.isBlank()) false else try {
        val pm = Utils.getApp().packageManager
        val ai = pm.getApplicationInfo(marketPkgName, 0)
        ai.flags and ApplicationInfo.FLAG_SYSTEM != 0
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
        false
    }
}

private fun getSamsungAppStoreIntent(packageName: String): Intent? {
    val intent = Intent(Intent.ACTION_VIEW)
    intent.setClassName(
        "com.sec.android.app.samsungapps",
        "com.sec.android.app.samsungapps.Main"
    )
    intent.data =
        Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=$packageName")
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    return if (getAvailableIntentSize(intent) > 0) {
        intent
    } else null
}

private fun getLeecoAppStoreIntent(packageName: String): Intent? {
    val intent = Intent().apply {
        setClassName(
            "com.letv.app.appstore",
            "com.letv.app.appstore.appmodule.details.DetailsActivity"
        )
        action = "com.letv.app.appstore.appdetailactivity"
        putExtra("packageName", packageName)
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    return if (getAvailableIntentSize(intent) > 0) {
        intent
    } else null
}